/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
Components.utils.import("resource:///modules/activity/activityModules.js");
Components.utils.import("resource:///modules/attachmentChecker.js");
Components.utils.import("resource:///modules/cloudFileAccounts.js");
Components.utils.import("resource:///modules/errUtils.js");
Components.utils.import("resource:///modules/folderUtils.jsm");
Components.utils.import("resource:///modules/iteratorUtils.jsm");
Components.utils.import("resource:///modules/mailServices.js");
Components.utils.import("resource:///modules/MailUtils.js");
Components.utils.import("resource://gre/modules/InlineSpellChecker.jsm");
Components.utils.import("resource://gre/modules/PluralForm.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource:///modules/editorUtilities.jsm");


Components.utils.import("resource:///modules/FeedUtils.jsm");
Components.utils.import("resource:///modules/gloda/dbview.js");
Components.utils.import("resource:///modules/MailConsts.js");



/**
 * interfaces
 */
const nsIMsgCompDeliverMode = Components.interfaces.nsIMsgCompDeliverMode;
const nsIMsgCompSendFormat = Components.interfaces.nsIMsgCompSendFormat;
const nsIMsgCompConvertible = Components.interfaces.nsIMsgCompConvertible;
const nsIMsgCompType = Components.interfaces.nsIMsgCompType;
const nsIMsgCompFormat = Components.interfaces.nsIMsgCompFormat;
const nsIAbPreferMailFormat = Components.interfaces.nsIAbPreferMailFormat;
const nsIPlaintextEditorMail = Components.interfaces.nsIPlaintextEditor;
const nsISupportsString = Components.interfaces.nsISupportsString;
const mozISpellCheckingEngine = Components.interfaces.mozISpellCheckingEngine;
const nsIMsgFolderObj= Components.interfaces.nsIMsgFolder;
/*邮件存储实现*/
function nsAttachmentOpener()
{
}

nsAttachmentOpener.prototype =
{
  QueryInterface: function(iid)
  {
    if (iid.equals(Components.interfaces.nsIURIContentListener) ||
        iid.equals(Components.interfaces.nsIInterfaceRequestor) ||
        iid.equals(Components.interfaces.nsISupports))
        return this;
    throw Components.results.NS_NOINTERFACE;
  },

  onStartURIOpen: function(uri)
  {
    return false;
  },

  doContent: function(contentType, isContentPreferred, request, contentHandler)
  {
    return false;
  },

  isPreferred: function(contentType, desiredContentType)
  {
    return false;
  },

  canHandleContent: function(contentType, isContentPreferred, desiredContentType)
  {
    return false;
  },

  getInterface: function(iid)
  {
    if (iid.equals(Components.interfaces.nsIDOMWindow))
      return window;
    else
      return this.QueryInterface(iid);
  },

  loadCookie: null,
  parentContentListener: null
}

function findIdentityListId()
{
  var AccAndIdentity=[{AccountId:"accountId", IdentityKey:"id", IdentityName:"emailName"}];  

  let accounts = allAccountsSorted(true);
  //alert(accounts.length);
  for (let acc = 0; acc < accounts.length; acc++) {
    let account = accounts[acc];
 
    let identities = toArray(fixIterator(account.identities,
                                         Components.interfaces.nsIMsgIdentity));
        
    if (identities.length == 0)
      continue;
     //alert(identities.length);
    for (let i = 0; i < identities.length; i++) {
      let identity = identities[i];
             //alert("i="+i);
            var step1Id=identity.identityName.split(">")[0];
      
            var step2Id=step1Id.split("<")[1];
    
      AccAndIdentity.push({AccountId:account,IdentityKey:identity.key, IdentityName:step2Id}) ;
    }
 }
 return AccAndIdentity;
}
function SaveK9mailMessage(accName,messageType)
{   
  //alert(1);
  var nsAttachmentOpener1= new nsAttachmentOpener();
  //var window1 = nsAttachmentOpener1.getInterface(Components.interfaces.nsIDOMWindow);
  var editor1 =document.getElementById("content-frame");
  /*
   * 解析XML数据
   * */
  xmlDoc = document.implementation.createDocument('','',null);
  if(xmlDoc != null)
  {
      xmlDoc.async = false;
      xmlDoc.load("test-002.xml");
  }
 /*get account and identity*/
  var  AccAndIdentity=findIdentityListId();
  var IdentityValue = null;
  var AccountValue =null; 
  var userName=null;
  for(var i=1;i<=AccAndIdentity.length;i++)
  {
      var accidentityObj=AccAndIdentity[i];
      if(accidentityObj.IdentityName==="lijinhai5566@163.com")
      {
          IdentityValue=MailServices.accounts.getIdentity(accidentityObj.IdentityKey);
          AccountValue=accidentityObj.AccountId;
          userName=accidentityObj.IdentityName.split("@")[0];
          //alert(IdentityValue);
          //alert(AccountValue);
          //alert(userName);
          break;        
      }
  }
  if(IdentityValue===null&&AccountValue===null)
  {
    IdentityValue = MailServices.accounts.getIdentity("id1");
    AccountValue = "account1";
  }
 // var IdentityValue = getCurrentIdentity();
  //var AccountValue = getCurrentAccountKey(); 
  
  msgCount=xmlDoc.getElementsByTagName("message");
  for (i=0;i<=msgCount.length;i++)
  { 
   let window1 = nsAttachmentOpener1.getInterface(Components.interfaces.nsIDOMWindow);   
   let params = Components.classes["@mozilla.org/messengercompose/composeparams;1"].createInstance(Components.interfaces.nsIMsgComposeParams);
   let msgWindow = Components.classes["@mozilla.org/messenger/msgwindow;1"]
                        .createInstance(Components.interfaces.nsIMsgWindow);
   let progress = Components.classes["@mozilla.org/messenger/progress;1"]
                             .createInstance(Components.interfaces.nsIMsgProgress);
   progress = null;
   gMsgCompose = MailServices.compose.initCompose(params, window1, editor1.docShell);  
   
  //var fccURI = aFolder.URI;
  //alert("fccURI="+fccURI);
  //msgCompFields.fcc2 = (msgCompFields.fcc2 == fccURI) ? "nocopy://" : fccURI;
      
    var msgCompFields = gMsgCompose.compFields;
    var msgSub= xmlDoc.getElementsByTagName("subject")[i].childNodes[0].nodeValue;
    var msgTo = xmlDoc.getElementsByTagName("to_list")[i].childNodes[0].nodeValue;
    var msgContent = xmlDoc.getElementsByTagName("html_content")[i].childNodes[0].nodeValue;
    //var fromvalue=xmlDoc.getElementsByTagName("reply_to_list")[i].childNodes[0].nodeValue;
    
    
    //msgCompFields.fcc2="mailbox://lijinhaiTestTB@pop3.163.com/Sent";//sent
    
    msgCompFields.subject =msgSub;
    msgCompFields.to = msgTo;
    msgCompFields.draftId = i;
    msgCompFields.body = msgContent;
    //msgCompFields.from = fromvalue;
    //alert("jinhai"+msgCompFields.from);
    /*附件存储实现*/
    //  
    //let attachment = Components.classes["@mozilla.org/messengercompose/attachment;1"]
                               //.createInstance(Components.interfaces.nsIMsgAttachment);
    //attachment.url = "file:///home/gyd/%E6%A1%8C%E9%9D%A2/gecko-sdk-i686-pc-linux-gnu-1.8.0.4.tar.bz2";                   
    //msgCompFields. addAttachment(attachment);  
    
    msgWindow.domWindow = window1;
    msgWindow.rootDocShell.allowAuth = true;
    /*
    const long Now = 0;
    const long Later = 1;
    const long Save = 2;
    const long SaveAs = 3;
    const long SaveAsDraft = 4;
    const long SaveAsTemplate = 5;
    const long SendUnsent = 6;
    const long AutoSaveAsDraft = 7;
    const long Background = 8;
   */
   if(messageType==="draft")
   {   
     gMsgCompose.SendMsg( 4,IdentityValue ,AccountValue,msgWindow, progress); 
   }else if(messageType==="inbox" )
   {
       msgCompFields.fcc2="mailbox://"+userName+"@pop3.163.com/Inbox";//inbox 
       gMsgCompose.SendMsg( 4,IdentityValue ,AccountValue,msgWindow, progress); 
   }
       
   else if(messageType==="send")
   {
       msgCompFields.fcc2="mailbox://"+userName+"@pop3.163.com/Sent";
        gMsgCompose.SendMsg( 4,IdentityValue ,AccountValue,msgWindow, progress); 
   }
         
   /*
    * delete many  message
    * 
   var treeTS=document.getElementById("threadTree");
    treeTS.view.selection.rangedSelect(0,8,true);
    goDoCommand('button_shiftDelete');//button_delete
    RestoreFocusAfterHdrButton();
     */
    msgCompFields.draftId=null;
    msgCompFields.subject=null;
    msgCompFields.to=null;
    msgCompFields.body =null;
    window1=null;
    //MailServices.mailSession.RemoveMsgWindow(msgWindow);
    msgWindow = null;
    msgWindow=null;
    //continue;
    //window1.close();
   /// gMsgCompose.CloseWindow(false);event.shiftKey ? 'button_shiftDelete' :
  
    }
    //alert("me");
}
